package com.example.springcloudresourceserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springcloudresourceserver.model.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.authserver.AuthorizationServerProperties;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;

@RestController
public class TokenController {

    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;

    @Autowired
    private AuthorizationServerProperties authorizationServerProperties;

    @Autowired
    private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<OAuth2AccessToken> login(@RequestBody LoginDTO loginDTO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new Exception("登录信息格式错误");
        }
        String clientAndSecret = oAuth2ClientProperties.getClientId().concat(":").concat(oAuth2ClientProperties.getClientSecret());
        clientAndSecret = "Basic " + Base64.getEncoder().encodeToString(clientAndSecret.getBytes(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization",clientAndSecret);

        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("username",loginDTO.getUsername());
        params.add("password",loginDTO.getPassword());
        params.add("grant_type", oAuth2ProtectedResourceDetails.getGrantType());
        /*params.add("scope","read");*/

        HttpEntity entity = new HttpEntity(params,headers);
        System.err.println(JSONObject.toJSONString(entity,true));
        ResponseEntity<OAuth2AccessToken> result = restTemplate.exchange(oAuth2ProtectedResourceDetails.getAccessTokenUri(), HttpMethod.POST,entity, OAuth2AccessToken.class);
        return result;
    }

}
